﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Linq.Expressions;
using Newtonsoft.Json;
using OA.Core;
using OA.Model;
using Z.EntityFramework.Plus;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.AspNetCore.Http;
using OA.Web.Code;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using OA.Core.Helper;
using OA.Core.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Infrastructure;
using System.Data.Common;
using OA.Model.Result;

namespace OA.Web.Areas.Admin.Controllers
{
    public class CustomFormController : BaseAdminController
    {
        private IMemoryCache _cache;
        public CustomFormController(ICookie cookie, IHttpContextAccessor accessor, IMemoryCache cache) : base(accessor, cookie, cache)
        {
            _cache = cache;
        }

        public IActionResult Index()
        {            
            return View();
        }

        public IActionResult GetData(string keyword, int page = 1, int limit = 20)
        {
            Expression<Func<CustomForm, bool>> where = m => true;
            if (!string.IsNullOrWhiteSpace(keyword))
            {
                where = m => m.Name.Contains(keyword);
            }
            PageList<SimpleCustomForm> list = this.GetPageList<CustomForm, SimpleCustomForm>(where, page, limit, SimpleCustomForm.Map);
            var result = new
            {
                code = "0",
                msg = "",
                count = list.RowCount,
                data = list.List
            };
            return Json(result);
        }

        [HttpGet]
        public IActionResult Create()
        {
            CustomForm model = new CustomForm();
            
            model.TableFields= new List<ExtendField>() {
                new ExtendField()
            };
            ViewBag.FormGroups = this.dbContextFactory.DbContext.FormGroup.Select(m => new ListItem() { Value = m.ID.ToString(), Text = m.Name }).ToList();

            
            return View(model);

        }

        [HttpPost]
        public IActionResult Create(CustomForm model)
        {
            BaseResult baseResult = new BaseResult();
            if (!ModelState.IsValid)
            {
                baseResult.Msg = this.GetModelStateError(ModelState);
                baseResult.State = 400;
                return Json(baseResult);
            }
            this.AddInfo<CustomForm>(model);
            baseResult.Msg = "表单创建成功";
            return Json(baseResult);

        }

        public IActionResult EditItem(int id)
        {
            var info=this.dbContextFactory.DbContext.CustomForm.Where(m => m.ID == id).FirstOrDefault();

            List<ExtendField> extendFields = new List<ExtendField>();
            if(info==null)
            {
                return Content("没有找到该单据");
            }

            if(!string.IsNullOrWhiteSpace(info.ExtendField))
            {
                extendFields = JsonHelper.DeserializeList<ExtendField>(info.ExtendField);
            }
            if (extendFields == null)
            {
                extendFields = new List<ExtendField>();
            }

            ViewBag.ExtendFields = extendFields;

            ViewBag.CustomForm = this.dbContextFactory.DbContext.CustomForm.Select(m => new ListItem() { Value = m.ID.ToString(), Text = m.Name }).ToList();

            ViewBag.TableInfos = this.dbContextFactory.DbContext.TableInfo.ToList();

            return View(info);
        }

        [HttpPost]
        public IActionResult ShowPreview(string infos)
        {
            ViewBag.TableInfos = this.dbContextFactory.DbContext.TableInfo.ToList();
            List<ExtendField> list = JsonHelper.DeserializeList<ExtendField>(infos);
            return View(list);
        }


        [HttpPost]
        public IActionResult SaveCustomForm(int id, string infos)
        {
            BaseResult baseResult = new BaseResult();
            List<ExtendField> list = JsonHelper.DeserializeList<ExtendField>(infos);
            if (list.Count == 0)
            {
                baseResult.State = 400;
                baseResult.Msg = "空的表格不能保存";
            }
            else
            {
                this.dbContextFactory.DbContext.CustomForm.Where(m => m.ID == id).Update(m => new CustomForm() { ExtendField = JsonHelper.SerializeObject(list) });
            }
            return Json(baseResult);
        }

        [HttpPost]
        public IActionResult SavePrintTemplate(int id, string html)
        {
            BaseResult baseResult = new BaseResult();
            this.dbContextFactory.DbContext.CustomForm.Where(m => m.ID == id).Update(m => new CustomForm() { PrintTemplate = html });
            return Json(baseResult);
        }

        [HttpGet]
        public IActionResult Edit(int id,string msg)
        {
            if (!string.IsNullOrWhiteSpace(msg))
            {
                ViewBag.Msg = msg;
            }
            CustomForm info = this.GetInfo<CustomForm>(id);
            if (info == null)
            {
                return Redirect("/Admin/Home/Info?msg=" + System.Web.HttpUtility.UrlEncode("沒有找到该商品类别", Encoding.UTF8));
            }            

            ViewBag.FormGroups = this.dbContextFactory.DbContext.FormGroup.Select(m => new ListItem() { Value = m.ID.ToString(), Text = m.Name }).ToList();
            return View(info);
        }

        [HttpPost]
        public IActionResult Edit(int id, CustomForm model)
        {
            BaseResult baseResult = new BaseResult();
            if (!ModelState.IsValid)
            {
                baseResult.Msg = this.GetModelStateError(ModelState);
                baseResult.State = 400;
                return Json(baseResult);
            }

            CustomForm infoPageGroup = this.GetInfo<CustomForm>(id);
            if (infoPageGroup == null)
            {
                baseResult.State = 400;
                baseResult.Msg = "沒有找到该表单信息";                
                return Json(baseResult);
            }
            this.Update<CustomForm>(infoPageGroup, model, null, new string[] { "ID", "ProcessPointContent", "PrintTemplate", "TableName", "ExtendField" });
            baseResult.Msg = "表单修改成功";
            return Json(baseResult);

        }

        [HttpGet]
        public IActionResult Delete(int id)
        {
            Expression<Func<CustomForm, bool>> where = m => m.ID == id;
            this.Delete<CustomForm>(where);
            return Json(new { State = 200, Msg = "表单删除成功" });
        }

        public IActionResult SetSort(int id, int sort)
        {
            try
            {
                CustomForm infoCustomForm = this.GetInfo<CustomForm>(id);
                if (infoCustomForm == null)
                {
                    return Json(new { State = 400, Msg = "没有找到相关的记录" });
                }
                CustomForm UpdateProduct = new CustomForm();
                UpdateProduct.Sort = sort;
                this.Update<CustomForm>(infoCustomForm, UpdateProduct, new string[] { "Sort" });
                return Json(new { State = 200, Msg = "" });

            }
            catch (Exception ex)
            {
                MyStatic.ExecptionQueue.Enqueue(ex);
                return Json(new { State = 400, Msg = "系统簸动" });
            }
        }


        [HttpGet]
        public IActionResult PrintTemplate(int id)
        {
            var customForm=this.dbContextFactory.DbContext.CustomForm.Where(m => m.ID == id).FirstOrDefault();
            return View(customForm);
        }


        [HttpGet]
        public IActionResult ApprovalProcess(int id)
        {
            var customForm = this.dbContextFactory.DbContext.CustomForm.Where(m => m.ID == id).FirstOrDefault();
            SysConfig infoConfig=this.dbContextFactory.DbContext.SysConfig.Where(m => m.Key == "BaseConfig").FirstOrDefault();
            var tables = this.dbContextFactory.DbContext.TableInfo.ToList();
            List<string> positionLevels = new List<string>();
            if (infoConfig!=null)
            {
                BaseConfig baseConfig = JsonHelper.DeserializeObj<BaseConfig>(infoConfig.Content);
                if (baseConfig != null)
                {
                    positionLevels = baseConfig.PositionLevel.Split(new string[] { ",", "，" }, StringSplitOptions.None).ToList();
                }
            }
            if(positionLevels==null|| positionLevels.Count==0)
            {
                return Content("请先配置好公司职层，配置路径为：系统配置=>基础配置=>公司职层");
            }
            ViewBag.PositionLevels = positionLevels;
            
            List<ExtendField> extendFields = JsonHelper.DeserializeList<ExtendField>(customForm.ExtendField);
            List<ApprovalProcessNodeInfo> nodes = new List<ApprovalProcessNodeInfo>();
            if(!string.IsNullOrWhiteSpace(customForm.ApprovalProcessNodeContent))
            {
                nodes = JsonHelper.DeserializeList<ApprovalProcessNodeInfo>(customForm.ApprovalProcessNodeContent);                
            }
            if(nodes==null||nodes.Count==0)
            {
                nodes = new List<ApprovalProcessNodeInfo>() { new ApprovalProcessNodeInfo() { Name = "上级审批", Type = 3, AtLeastOneSuperior = true, LastPositionLevel = positionLevels[positionLevels.Count - 2] }};               
            }
            ViewBag.Nodes = nodes;
            ViewBag.NewNodeStr = JsonHelper.ToBase64(new ApprovalProcessNodeInfo() { Name = "新节点", Type = 1 });
            List<SelectList2> selectList = new List<SelectList2>();//属性options
            List<int> compareType = new List<int>() { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 21, 22, 23, 24, 25, 69, 70 };
            List<SelectList2> listItem = extendFields.Where(m => compareType.Contains(m.Type)).Select(m => new SelectList2() { id = m.Attribute, name = m.Name, spread = false }).ToList();
             
            listItem.Add(new SelectList2() { id = "Department_2", name = "二级部门", spread = false });
            listItem.Add(new SelectList2() { id = "Department_3", name = "三级部门", spread = false });
            listItem.Add(new SelectList2() { id = "Approver", name = "审批岗位", spread = false });
            listItem.Add(new SelectList2() { id = "VirtualLevel", name = "虚拟职层", spread = false });

            #region 过滤器下来数据源
            Dictionary<string, List<XmSelectNode>> dicOptions = new Dictionary<string, List<XmSelectNode>>();
            var departments = this.dbContextFactory.DbContext.Department.Where(m => m.ParentDepartmentID == 0).Select(m => new { name = m.Name, value = m.ID}).ToList();
             
            var department_1 = departments.Select(m => m.value).ToList();
            departments = this.dbContextFactory.DbContext.Department.Where(m => department_1.Contains(m.ParentDepartmentID)).Select(m => new { name = m.Name, value = m.ID}).ToList();
            dicOptions.Add("Department_2", departments.Select(m => new XmSelectNode() { name = m.name, value = m.value.ToString(), selected = false }).ToList());

            var department_2 = departments.Select(m => m.value).ToList();
            departments = this.dbContextFactory.DbContext.Department.Where(m => department_2.Contains(m.ParentDepartmentID)).Select(m => new { name = m.Name, value = m.ID}).ToList();
            dicOptions.Add("Department_3", departments.Select(m => new XmSelectNode() { name = m.name, value = m.value.ToString(), selected = false }).ToList());

            var department_3 = departments.Select(m => m.value).ToList();
            departments = this.dbContextFactory.DbContext.Department.Where(m => department_3.Contains(m.ParentDepartmentID)).Select(m => new { name = m.Name, value = m.ID}).ToList();
            dicOptions.Add("Department_4", departments.Select(m => new XmSelectNode() { name = m.name, value = m.value.ToString(), selected = false }).ToList());

            //dicOptions.Add("Department_4", departments.Select(m => new XmSelectNode() { name = m.name, value = m.value.ToString(), selected = false }).ToList());

            var selectControls = extendFields.Where(m => m.Type == 3 || m.Type == 25).ToList();
            foreach (var item in selectControls)
            {
                if(!dicOptions.ContainsKey(item.Attribute)&&!string.IsNullOrWhiteSpace(item.Values))
                {
                    if(!item.Values.StartsWith("http://")&& !item.Values.StartsWith("https://"))
                    {
                        dicOptions.Add(item.Attribute, item.Values.Split(new string[] { ",", "，" }, StringSplitOptions.None).Select(m => new XmSelectNode() { name = m, value = m, selected = false }).ToList());
                    }                    
                }
            }

            //虚拟职层
            dicOptions.Add("VirtualLevel",BaseConfig.PositionLevel.Split(new string[] { ",", "，" }, StringSplitOptions.None).Select(m => new XmSelectNode() { name = m, value = m, selected = false }).ToList());

            #endregion


            selectList.Add(new SelectList2() { id="_top",name="基础属性",spread=true,children= listItem });
            var extendFields_1 = extendFields.Where(m => m.Type != 99).ToList();
            var extendFields_2 = extendFields.Where(m => m.Type == 99).ToList();
            foreach (var item in extendFields_2)
            {
                int tableid=0;
                if(Int32.TryParse(item.Values,out tableid))
                {
                    var table = tables.Where(m => m.ID == tableid).FirstOrDefault();
                    if(table!=null)
                    {
                        List<SelectList2> list = new List<SelectList2>();
                        item.DefaultValue = table.ConfigContent;
                        List<ExtendField> tableFields = JsonHelper.DeserializeList<ExtendField>(table.ConfigContent);
                        foreach (var item2 in tableFields)
                        {
                            if(compareType.Contains(item2.Type))
                            {
                                list.Add(new SelectList2() { name= item2.ParentName + "-" + item2.Name, id= item.Attribute + "@" + item2.Attribute, spread = false });
                            }
                            if((item2.Type==2||item2.Type==21)&&item2.IsSummarizing)
                            {
                                list.Add(new SelectList2() { name = item2.ParentName + "-" + item2.Name + "-汇总", id = item.Attribute + "@" + item2.Attribute + "@All", spread = false });
                            }
                            if(item2.Type==69)
                            {
                                list.Add(new SelectList2() { name = item2.Name + "-汇总", id = item.Attribute + "@" + item2.Attribute + "@Total", spread = false });
                            }
                            if(item2.Type==3||item2.Type==25)
                            {
                                if (!item2.Values.StartsWith("http://") && !item2.Values.StartsWith("https://"))
                                {
                                    string key = item.Attribute + "@" + item2.Attribute;
                                    if(!dicOptions.ContainsKey(key))
                                    {
                                        dicOptions.Add(item.Attribute + "@" + item2.Attribute, item2.Values.Split(new string[] { ",", "，" }, StringSplitOptions.None).Select(m => new XmSelectNode() { name = m, value = m, selected = false }).ToList());
                                    }
                                }
                            }
                        }
                        selectList.Add(new SelectList2() { id = item.Attribute, name = item.Name, spread = true, children = list });
                    }
                }                
            }
            StringBuilder sbOption = new StringBuilder();
            sbOption.Append("<option value=\"\">请选择需要比对的属性</option>");
            foreach (var item in selectList)
            {
                sbOption.Append($"<optgroup label=\"{item.name}\">");
                foreach (var item2 in item.children)
                {
                    sbOption.Append($"<option value=\"{item2.id}\">{item2.name}</option>");
                }
                sbOption.Append("</optgroup>");
            }
            ViewBag.CompareList = sbOption.ToString();
            ViewBag.ExtendFields = extendFields_1;
            ViewBag.Tables = extendFields_2;
            ViewBag.DicOptions = JsonHelper.SerializeObject(dicOptions);
            return View(customForm);
        }

        [HttpPost]
        public IActionResult SaveApprovalProcess(int id, string infos)
        {
            BaseResult baseResult = new BaseResult();
            List<ApprovalProcessNodeInfo> list = new List<ApprovalProcessNodeInfo>();
            try
            {
                List<string> result = JsonHelper.DeserializeList<string>(infos);
                foreach (var item in result)
                {
                    ApprovalProcessNodeInfo info = item.FromBase64<ApprovalProcessNodeInfo>();
                    if(info!=null)
                    {
                        list.Add(info);
                    }
                }
                this.dbContextFactory.DbContext.CustomForm.Where(m => m.ID == id).Update(m => new CustomForm() { ApprovalProcessNodeContent = JsonHelper.SerializeObject(list) });
            }
            catch(Exception ex)
            {
                baseResult.State = 400;
                baseResult.Msg = ex.ToString();
            }
            return Json(baseResult);

        }



        [HttpPost]
        public IActionResult PrintTemplate(int id,string content)
        {
            BaseResult baseResult = new BaseResult();
            this.dbContextFactory.DbContext.CustomForm.Where(m => m.ID == id).Update(m => new CustomForm() { PrintTemplate = content });
            return Json(baseResult);
        }

        [HttpPost]
        public IActionResult PrintTemplatePreview(string html)
        {
            ViewBag.Html = html;
            return View();
        }
        


        [HttpGet]
        public IActionResult CreateDatabaseTable(int id)
        {
            BaseResult baseResult = new BaseResult();
            var customForm = this.dbContextFactory.DbContext.CustomForm.Where(m => m.ID == id).FirstOrDefault();
            if(customForm==null)
            {
                baseResult.Msg = "表单数据未找到！";
                return Json(baseResult);
            }
            else
            {
                string sql = @"CREATE TABLE [dbo].[{0}](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[No] [nvarchar](20) NOT NULL,
	[Title] [nvarchar](50) NOT NULL,
	[ApplicationDate] [datetime] NULL,
	[PositionID] [int] NOT NULL,
	[Sponsor] [nvarchar](10) NULL,
	[DepartmentID] [int] NOT NULL,
	[Extension] [nvarchar](max) NULL,
	[Status] [int] NOT NULL,
	[CreateDateTime] [datetime] NOT NULL,
	[CurrentApprover] [nvarchar](100) NULL,
	[SponsorName] [nvarchar](20) NULL,
	[Communicator] [nvarchar](100) NULL,
	[FinishTime] [datetime] NULL,
	[Remark] [nvarchar](100) NULL,
	[SupervisingMember] [nvarchar](max) NULL,
	[SupervisingEmpID] [nvarchar](100) NULL,
	[TreeContent] [nvarchar](3000) NULL,
	[PdfUrl] [nvarchar](100) NULL,
	[PdfStatus] [int] NOT NULL,
	[CustomFormContent] [nvarchar](max) NULL,
	[ApprovalID] [int] NULL,
	[DepartmentName] [nvarchar](200) NULL,
	[ApprovalNodeContent] [nvarchar](max) NULL,
 CONSTRAINT [PK_dbo.{0}] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
         ";
                try
                {
                    sql = string.Format(sql, "Z_" + customForm.TableName);
                    this.dbContextFactory.DbContext.Database.GetDbConnection().Open();
                    DbCommand dbCommand = this.dbContextFactory.DbContext.Database.GetDbConnection().CreateCommand();
                    dbCommand.CommandText = sql;
                    dbCommand.ExecuteNonQuery();
                    this.dbContextFactory.DbContext.Database.GetDbConnection().Close();
                    baseResult.Msg = "生成数据库表成功！";
                    return Json(baseResult);
                }
                catch(Exception ex)
                {
                    baseResult.State = 400;
                    baseResult.Msg = ex.ToString();
                    return Json(baseResult);
                }
               

            }

           
        }
        

    }
}